from rest_framework import serializers
from django.contrib.auth import authenticate
from rbac.models import User, Role, Permission


class UserRegistrationSerializer(serializers.ModelSerializer):
    """用户注册序列化器"""
    password = serializers.CharField(write_only=True, min_length=6)
    password_confirm = serializers.CharField(write_only=True)

    class Meta:
        model = User
        fields = ('username', 'email', 'password', 'password_confirm', 'phone')

    def validate(self, attrs):
        if attrs['password'] != attrs['password_confirm']:
            raise serializers.ValidationError("密码不匹配")
        return attrs

    def create(self, validated_data):
        validated_data.pop('password_confirm')
        user = User.objects.create_user(**validated_data)
        return user


class UserLoginSerializer(serializers.Serializer):
    """用户登录序列化器"""
    username = serializers.CharField()
    password = serializers.CharField()

    def validate(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')

        if username and password:
            user = authenticate(username=username, password=password)
            if not user:
                raise serializers.ValidationError('用户名或密码错误')
            if not user.is_active:
                raise serializers.ValidationError('用户账户已被禁用')
            attrs['user'] = user
        else:
            raise serializers.ValidationError('必须提供用户名和密码')
        
        return attrs


class UserSerializer(serializers.ModelSerializer):
    """用户信息序列化器"""
    roles = serializers.SerializerMethodField()
    permissions = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'phone', 'avatar', 'is_active', 
                 'date_joined', 'roles', 'permissions')

    def get_roles(self, obj):
        """获取用户角色"""
        roles = obj.roles.all()
        return [{'id': role.id, 'name': role.name, 'code': role.code} for role in roles]

    def get_permissions(self, obj):
        """获取用户权限"""
        permissions = Permission.objects.filter(
            role__users=obj
        ).distinct()
        return [{'id': perm.id, 'name': perm.name, 'code': perm.code} for perm in permissions]
